#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化的任务检查脚本
专门检查指定任务的执行情况和结果
"""

import sys
import os
import requests
import json

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# API基础URL
BASE_URL = "http://localhost:5000/api/v1/prediction"

def check_task_via_api(task_id):
    """通过API检查任务状态和结果"""
    print(f"🔍 通过API检查任务: {task_id}")
    print("=" * 50)
    
    try:
        # 1. 检查任务状态
        print("📊 查询任务状态...")
        status_response = requests.get(f"{BASE_URL}/tasks/{task_id}/status", timeout=10)
        
        if status_response.status_code == 200:
            task_data = status_response.json()['data']
            print("✅ 任务信息:")
            print(f"   ID: {task_data['task_id']}")
            print(f"   名称: {task_data['task_name']}")
            print(f"   类型: {task_data['task_type']}")
            print(f"   状态: {task_data['status']}")
            print(f"   进度: {task_data['progress']}%")
            print(f"   当前步骤: {task_data.get('current_step', '无')}")
            print(f"   创建时间: {task_data.get('created_at', '无')}")
            print(f"   开始时间: {task_data.get('started_at', '无')}")
            print(f"   完成时间: {task_data.get('completed_at', '无')}")
            
            if task_data.get('error_message'):
                print(f"   ❌ 错误信息: {task_data['error_message']}")
            
            # 显示任务参数
            print(f"\n📋 任务参数:")
            print(f"   公司IDs: {task_data.get('company_ids', [])}")
            print(f"   产品IDs: {task_data.get('product_ids', [])}")
            print(f"   预测年份: {task_data.get('prediction_years', [])}")
            if task_data.get('description'):
                print(f"   描述: {task_data['description']}")
            
            # 2. 如果任务完成，检查结果
            if task_data['status'] == 'completed':
                print(f"\n📈 查询预测结果...")
                results_response = requests.get(f"{BASE_URL}/tasks/{task_id}/results", timeout=10)
                
                if results_response.status_code == 200:
                    results_data = results_response.json()['data']
                    results = results_data['results']
                    
                    print(f"✅ 预测结果:")
                    print(f"   结果数量: {len(results)}")
                    
                    if results:
                        # 按板块分组显示
                        sectors = {}
                        for result in results:
                            sector = result.get('company_name', 'Unknown')
                            if sector not in sectors:
                                sectors[sector] = []
                            sectors[sector].append(result)
                        
                        print(f"\n📊 结果详情:")
                        for sector, sector_results in sectors.items():
                            print(f"   {sector}:")
                            for result in sector_results:
                                year = result.get('prediction_year', 'N/A')
                                sales = result.get('predicted_sales_amount', 0)
                                profit = result.get('predicted_unit_profit', 0)
                                confidence = result.get('confidence_score', 0)
                                print(f"     {year}年: 销售额{sales:.2f}亿元, 净利润{profit:.2f}亿元, 置信度{confidence:.3f}")
                    else:
                        print("   ❌ 无预测结果数据")
                        
                else:
                    print(f"   ❌ 获取结果失败: {results_response.status_code} - {results_response.text}")
            
            elif task_data['status'] == 'failed':
                print(f"\n❌ 任务执行失败")
                if task_data.get('error_message'):
                    print(f"错误详情: {task_data['error_message']}")
            
            elif task_data['status'] in ['pending', 'running']:
                print(f"\n⏳ 任务还在执行中...")
                print(f"当前进度: {task_data['progress']}%")
                print(f"当前步骤: {task_data.get('current_step', '无')}")
            
        else:
            print(f"❌ 查询任务状态失败: {status_response.status_code} - {status_response.text}")
            
    except requests.exceptions.RequestException as e:
        print(f"❌ 网络请求异常: {str(e)}")
        print("请确保后端服务正在运行 (http://localhost:5000)")
    except Exception as e:
        print(f"❌ 检查异常: {str(e)}")

def list_all_tasks():
    """列出所有任务"""
    print("📋 列出所有预测任务")
    print("=" * 50)
    
    try:
        response = requests.get(f"{BASE_URL}/tasks?page=1&page_size=20", timeout=10)
        
        if response.status_code == 200:
            data = response.json()['data']
            tasks = data['items']
            
            print(f"📊 共找到 {data['total']} 个任务，显示前 {len(tasks)} 个:")
            print()
            
            for i, task in enumerate(tasks, 1):
                print(f"{i}. {task['task_id'][:8]}...")
                print(f"   名称: {task['task_name']}")
                print(f"   类型: {task['task_type']}")
                print(f"   状态: {task['status']}")
                print(f"   创建时间: {task.get('created_at', 'N/A')}")
                print()
        else:
            print(f"❌ 获取任务列表失败: {response.status_code} - {response.text}")
            
    except Exception as e:
        print(f"❌ 列出任务异常: {str(e)}")

def main():
    """主函数"""
    print("🔍 预测任务检查工具")
    print("=" * 50)
    
    if len(sys.argv) > 1:
        task_id = sys.argv[1]
        check_task_via_api(task_id)
    else:
        print("📋 未指定任务ID，显示所有任务:")
        print()
        list_all_tasks()
        print()
        print("💡 使用方法:")
        print("   python check_task_simple.py <task_id>")
        print("   例如: python check_task_simple.py bba1d445-cf12-44b9-9613-f15c18bb5e2e")

if __name__ == "__main__":
    main()
